In this week, we focused on Embedded Programming. The goal was to program three different small circuits with Tinkercad, the first one being just a small depiction of how the programm works, the second one being a game of our choice using leds and buttons, the last one being a representation of the circuit we may use to create our final project. For the second game I decided to create a "Whack a Mole" like game, where you have to press buttons depending on which led is led up. In the following steps I will show how I created each one of these circuits.
Step 1.1: Setting up the project
Before writing any code, I had to build the basic parts of the project. I set up a new project in Tinkercad and added an Arduino, a small circuit board as well as two buttons and two resistors. I also connected them with the 5V panel of the Arduino to give the buttons a power supply.
Step 1.2: Adding LEDs
Now I added 4 LEDs and a resistor for each of them. I connected the to the pins 13-10 of the Arduino. As you can see I forgot tzo connect them to the Ground, I will fix this in a future step.
Step 1.3: Connecting the buttons
I connected the buttons to the pins 2 and 3.
Step 1.4: Starting with the code
Now that the project is set up I started writing the code. In the basic setup here I wrote some variables for each of the connected pins.
Step 1.5: Reading button inputs
I changed the loop function to constantly check for inputs from the two buttons.
Step 1.6: Implementing logic
I added a few if clauses, which change the lighted LEDs, based on the states of the buttons. The code is now finished.
// C++ code
//
const int led1 = 13;
const int led2 = 12;
const int led3 = 11;
const int led4 = 10;
const int btnPin1 = 3;
const int btnPin2 = 2;
int btnValue1 = 0;
int btnValue2 = 0;
void setup()
{
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
}
void loop()
{
btnValue1 = digitalRead(btnPin1);
btnValue2 = digitalRead(btnPin2);
if(btnValue1 == LOW){
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
}
else{
digitalWrite(led2, HIGH);
digitalWrite(led1, LOW);
}
if(btnValue2 == LOW) {
digitalWrite(led3, HIGH);
digitalWrite(led4, LOW);
}
else{
digitalWrite(led3, LOW);
digitalWrite(led4, HIGH);
}
}
Step 1.7: Final Result
The two buttons now control all of the LEDs.